package UIFree.controls.popupMenu {
	import UIFree.ObjectEvent;
	import UIFree.abox.uif_abox;
	import UIFree.controls.uif_button;
	import UIFree.controls.uif_gbutton;
	import UIFree.controls.uif_label;
	import UIFree.controls.uif_leavesBlock;
	import UIFree.controls.uif_popupMenu;
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	
	import UIUtils.uif_util;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class uif_mainMenu extends uif_ecomponent {
		private var _menu: Array;
		private var _submenuOptions: Object;
		
		public function uif_mainMenu(parent:uif_component, a_menu: Array, a_submenuOptions: Object=null) {
			
			var inner: Rectangle = parent.getInner();
			_menu = a_menu;
			super(parent, inner.x, inner.y, inner.width, inner.height, 'mainMenu');
			_submenuOptions = uif_util.union({
				orientation	: uif_popupMenu.BOTTOMPOSITION,
				itemClass	: uif_gbutton,
				showEvent	: MouseEvent.ROLL_OVER
			}, a_submenuOptions);
			createComponents(getInner());
		}
		
		public function get menuTree(): Array {
			return _menu;
		}
		
		private function createSubMenu(a_parent: uif_ecomponent, subMenu: Array): void {
			var _menu: uif_popupMenu = new uif_popupMenu(app, _submenuOptions, 100, 100, 'popupmenu');
			
			_menu.listMenu = subMenu;
			
			_menu.activeControl = a_parent;
			_menu.addEvent(Event.SELECT, doSelect);
		}
		
		protected function doSelect(e: ObjectEvent): void {
			dispatchEvent(new ObjectEvent(Event.SELECT, e.object));
		}
		
		protected function createComponents(rect:Rectangle):void {
			var itemStyle: Object = app.styleByObj(style.item);
			var ax: int = rect.x;
			_menu.forEach(function(a_item: Object, i: int, arr: Array): void {
				var size: Point = uif_component.getTextSize(a_item.caption, itemStyle.text_format.font, itemStyle.text_format.size);
				var space: Number = app.getStyleSpace(itemStyle, true) * 2;
				uif_util.getClass(a_item.itemClass, uif_gbutton);
				var item: uif_label = new (uif_util.getClass(a_item.itemClass, uif_gbutton))(This, ax, rect.y, size.x + space, rect.height, style.item);
				item.text = a_item.caption;
				item._data = a_item; 
				item.addEvent(MouseEvent.CLICK, doItemClick);
				if (a_item.submenu) createSubMenu(item, a_item.submenu);
				ax += size.x + space;
				
			});
		}
		
		protected function doItemClick(e: Event): void {
			var a_data: Object = (e.target as uif_component)._data;
			dispatchEvent(new ObjectEvent(Event.SELECT, a_data));
		}
	}
}